# -*- coding: utf-8 -*-
# @version : 1.0
# @File    : voice_trans.py
# @Date    : 2024/12/3 16:49
# @Author  : GlenZhao
# @Desc    :
import json
import time
from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from application.settings import ALIYUN_VOP, ALIYUN_OSS

def voice_trans(file_link):
    # 地域ID，固定值。
    region_id = "cn-shanghai"
    product = "nls-filetrans"
    domain = "filetrans.cn-shanghai.aliyuncs.com"
    api_version = "2018-08-17"
    post_request_action = "SubmitTask"
    get_request_action = "GetTaskResult"

    # 响应参数
    key_task = "Task"
    key_task_id = "TaskId"
    key_status_text = "StatusText"
    key_result = "Result"
    # 状态值
    status_success = "SUCCESS"
    status_running = "RUNNING"
    status_queueing = "QUEUEING"
    # 创建AcsClient实例
    client = AcsClient(ALIYUN_OSS['accessKeyId'], ALIYUN_OSS['accessKeySecret'], region_id)
    # 提交录音文件识别请求
    post_request = CommonRequest()
    post_request.set_domain(domain)
    post_request.set_version(api_version)
    post_request.set_product(product)
    post_request.set_action_name(post_request_action)
    post_request.set_method('POST')
    # 新接入请使用4.0版本，已接入（默认2.0）如需维持现状，请注释掉该参数设置。
    # 设置是否输出词信息，默认为false，开启时需要设置version为4.0。
    task = {"appkey": ALIYUN_VOP['appKey'], "file_link": file_link, "version": "4.0", "enable_words": False}
    # 开启智能分轨，如果开启智能分轨，task中设置KEY_AUTO_SPLIT为True。
    # task = {KEY_APP_KEY : appKey, KEY_FILE_LINK : file_link, KEY_VERSION : "4.0", KEY_ENABLE_WORDS : False, "auto_split" : True}
    task = json.dumps(task)
    print(task)
    post_request.add_body_params(key_task, task)
    task_id = ""
    try:
        post_response = client.do_action_with_exception(post_request)
        post_response = json.loads(post_response)
        print(post_response)
        status_text = post_response[key_status_text]
        if status_text == status_success:
            print("录音文件识别请求成功响应！")
            task_id = post_response[key_task_id]
        else:
            print("录音文件识别请求失败！")
            return
    except ServerException as e:
        print(e)
    except ClientException as e:
        print(e)
    # 创建CommonRequest，设置任务ID。
    get_request = CommonRequest()
    get_request.set_domain(domain)
    get_request.set_version(api_version)
    get_request.set_product(product)
    get_request.set_action_name(get_request_action)
    get_request.set_method('GET')
    get_request.add_query_param(key_task_id, task_id)
    # 提交录音文件识别结果查询请求
    # 以轮询的方式进行识别结果的查询，直到服务端返回的状态描述符为"SUCCESS"、"SUCCESS_WITH_NO_VALID_FRAGMENT"，
    # 或者为错误描述，则结束轮询。
    status_text = ""
    while True:
        get_response = client.do_action_with_exception(get_request)
        get_response = json.loads(get_response)
        print(get_response)
        status_text = get_response[key_status_text]
        if status_text == status_running or status_text == status_queueing:
            # 继续轮询
            time.sleep(2)
        else:
            # 退出轮询
            break

    if status_text == status_success:
        print("录音文件识别成功！")
        return get_response['Result']

    raise Exception("录音文件识别失败！")